package cn.yr.common.core.manager;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.yr.common.core.constant.CommonConstants;
import cn.yr.common.core.utils.jwt.JwtUtil;
import cn.yr.common.core.domain.dto.SysUserDto;
import cn.yr.common.core.utils.ServletUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 根据token获取用户相关信息
 *
 * @author Lang 1102076808@qq.com
 * @date 2021-04-07 20:15
 */
@Component
public class AuthUserManager {

	@Autowired
	AuthCacheManager authCacheManager;

	/**
	 * @Description 获取用户ID
	 * @author Lang
	 * @Date 2020/7/10 21:50
	 */
	public Long uid(){
		HttpServletRequest request = ServletUtil.getRequest();
		return uid(request);
	}

	public Long uid(HttpServletRequest request){
		String uid = request.getHeader(CommonConstants.JWT_USERID);
		if(StrUtil.isNotBlank(uid)){
			return Long.parseLong(uid);
		}
		String token = getRequestToken(request);
		uid = JwtUtil.getUid(token);
		if(StrUtil.isEmpty(uid)){
			return null;
		}
		return Long.parseLong(uid);
	}

	public String getUserName(){
		return getUser().getSysUser().getUserName();
	}

	/**
	 * @Description 获取用户
	 * @author Lang
	 * @Date 2020/7/10 21:51
	 */
	public SysUserDto getUser(){
		HttpServletRequest request = ServletUtil.getRequest();
		return getUser(request);
	}

	public SysUserDto getUser(HttpServletRequest request){
		Long uid = uid(request);
		if(ObjectUtil.isEmpty(uid)){
			return null;
		}
		return authCacheManager.getUser(uid.toString());
	}

	/**
	 * @Description 获取token
	 * @author Lang
	 * @Date 2020/7/9 22:54
	 */
	public String getRequestToken(HttpServletRequest httpRequest){
		//从header中获取token
		String token = httpRequest.getHeader(CommonConstants.HEADER);
		//如果header中不存在token，则从参数中获取token
		if(token==null){
			token = httpRequest.getParameter(CommonConstants.HEADER);
		}
		return token;
	}

	public void updateUser(SysUserDto sysUserDto){
		authCacheManager.putUser(uid().toString(),sysUserDto);
	}

}
